package com.woniu51.order.config;

import org.springframework.amqp.core.*;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 杨光
 * @date 2022年04月08日 17:42
 */
@Configuration
public class RabbitMqConfig {


    //延时交换机
    public static final String DELAY_EXCHANGE = "woniu51.spring.boot.delay.exchange";//
    //死信交换机
    public static final String DLX_EXCHANGE = "woniu51.spring.boot.dlx.exchange";

    //延时队列
    public static final String DELAY_QUEUE="woniu51.spring.boot.delay.queue";
    //死信队列
    public static final String DLX_QUEUE="woniu51.spring.boot.dlx.queue";
    //延时队列routingkey
    public static final String DELAY_ROUTING_KEY="woniu51.spring.boot.delay.routingkey";
    //死信队列routingkey
    public static final String DLX_ROUTING_KEY="woniu51.spring.boot.dlx.routingkey";


    //定义死信交换机
    @Bean("dlxExchange")
    public DirectExchange dlxExchange(){
        return new DirectExchange(DLX_EXCHANGE);
    }
    //定义业务交换机
    @Bean("delayExchange")
    public DirectExchange delayExchange(){
        return new DirectExchange(DELAY_EXCHANGE);
    }

    //死信队列
    @Bean("dlxQueue")
    public Queue dlxQueue(){
        return QueueBuilder.durable(DLX_QUEUE).build();
    }

    //延时队列
    @Bean("delayQueue")
    public Queue delayQueue(){

        Map<String,Object> args = new HashMap();
        args.put("x-message-ttl",50000);//超时时间30秒
        args.put("x-dead-letter-exchange",DLX_EXCHANGE);
        args.put("x-dead-letter-routing-key",DLX_ROUTING_KEY);//死信交换机发给死信队列时候的routingkey必须用这个

        return QueueBuilder.durable(DELAY_QUEUE).withArguments(args).build();
    }

    //绑定延时队列和交换机
    @Bean
    public Binding delayQueueBinding(
            @Qualifier("delayQueue") Queue queue,
            @Qualifier("delayExchange") DirectExchange exchange
    ){
        //链式编程
        return BindingBuilder.bind(queue).to(exchange).with(DELAY_ROUTING_KEY);
    }


    //绑定死信队列和死信交换机
    @Bean
    public Binding dlxQueueBinding(
            @Qualifier("dlxQueue") Queue queue,
            @Qualifier("dlxExchange") DirectExchange exchange
    ){
        //链式编程
        return BindingBuilder.bind(queue).to(exchange).with(DLX_ROUTING_KEY);
    }
}
